package com.guomei.service.curse.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.curse.Coupon;
import com.guomei.mapper.curse.CouponMapper;
import com.guomei.service.curse.CouponService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 优惠券服务实现类
 */
@Service
@Slf4j
@Transactional
public class CouponServiceImpl implements CouponService {
    @Resource
    private CouponMapper couponMapper;

    @Override
    public Coupon getById(Long id) {
        if (id == null) {
            return null;
        }
        return couponMapper.selectById(id);
    }

    @Override
    public List<Coupon> getAvailableByCourseId(Long courseId) {
        return couponMapper.selectAvailableByCourseId(courseId);
    }

    @Override
    public List<Coupon> getAll() {
        return couponMapper.selectAll();
    }

    @Override
    public Result<?> getByCondition(Coupon coupon) {
        PageHelper.startPage(coupon.getPageNum(), coupon.getPageSize());
        List<Coupon> coupons = couponMapper.selectByCondition(coupon);
        // 封装分页结果到PageData
        PageData<Coupon> pageData = new PageData<>();
        PageInfo<Coupon> pageInfo = new PageInfo<>(coupons);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(coupon.getPageNum());
        pageData.setPageSize(coupon.getPageSize());
        return Result.success(pageData);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> save(Coupon coupon) {
        // 验证必填字段
        if (coupon == null || coupon.getCouponName() == null || coupon.getCouponName().trim().isEmpty()
                || coupon.getCouponType() == null || coupon.getDiscountValue() == null
                || coupon.getStartTime() == null || coupon.getEndTime() == null
                || coupon.getTotalCount() == null || coupon.getTotalCount() <= 0) {
            return Result.fail("必填字段不能为空");
        }

        // 验证时间有效性
        if (coupon.getStartTime().isAfter(coupon.getEndTime())) {
            return Result.fail("优惠券开始时间不能早于结束时间");
        }

        LocalDateTime now = LocalDateTime.now();
        coupon.setCreatedTime(now);
        coupon.setUpdatedTime(now);

        // 设置默认值
        if (coupon.getMinPurchase() == null) {
            coupon.setMinPurchase(BigDecimal.ZERO);
        }
        if (coupon.getUsedCount() == null) {
            coupon.setUsedCount(0);
        }
        if (coupon.getStatus() == null) {
            coupon.setStatus((short) 1); // 默认启用
        }

        return couponMapper.insert(coupon) > 0 ? Result.success() : Result.fail("添加失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSave(List<Coupon> coupons) {
        if (coupons == null || coupons.isEmpty()) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        for (Coupon coupon : coupons) {
            // 验证必填字段
            if (coupon.getCouponName() == null || coupon.getCouponName().trim().isEmpty()
                    || coupon.getCouponType() == null || coupon.getDiscountValue() == null
                    || coupon.getStartTime() == null || coupon.getEndTime() == null
                    || coupon.getTotalCount() == null || coupon.getTotalCount() <= 0) {
                return false;
            }

            // 验证时间有效性
            if (coupon.getStartTime().isAfter(coupon.getEndTime())) {
                return false;
            }

            coupon.setCreatedTime(now);
            coupon.setUpdatedTime(now);

            // 设置默认值
            if (coupon.getMinPurchase() == null) {
                coupon.setMinPurchase(BigDecimal.ZERO);
            }
            if (coupon.getUsedCount() == null) {
                coupon.setUsedCount(0);
            }
            if (coupon.getStatus() == null) {
                coupon.setStatus((short) 1);
            }
        }

        return couponMapper.batchInsert(coupons) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> update(Coupon coupon) {
        if (coupon == null || coupon.getId() == null) {
            return Result.fail("优惠券ID不能为空");
        }

        // 验证时间有效性
        if (coupon.getStartTime() != null && coupon.getEndTime() != null
                && coupon.getStartTime().isAfter(coupon.getEndTime())) {
            return Result.fail("优惠券开始时间不能早于结束时间");
        }

        coupon.setUpdatedTime(LocalDateTime.now());
        return couponMapper.updateById(coupon) > 0 ? Result.success() : Result.fail("更新失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUsedCount(Long id, int count) {
        if (id == null || count <= 0) {
            return false;
        }

        // 先查询优惠券信息，判断是否还有剩余
        Coupon coupon = getById(id);
        if (coupon == null || coupon.getUsedCount() + count > coupon.getTotalCount()) {
            return false;
        }

        return couponMapper.updateUsedCount(id, count) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> removeById(Long id) {

        return couponMapper.deleteById(id) > 0 ? Result.success() : Result.fail("删除失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemove(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return couponMapper.batchDelete(ids) > 0;
    }

    @Override
    public void incrementUsedCount(Long couponId) {
        if (couponId == null) {
            return;
        }
        couponMapper.incrementUsedCount(couponId);
    }

    @Override
    public boolean checkCouponAvailable(Long couponId, Long courseId, BigDecimal amount) {
        if (couponId == null) {
            return false;
        }

        Coupon coupon = getById(couponId);
        if (coupon == null) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        // 检查状态、时间、使用数量
        if (coupon.getStatus() != 1
//                || now.isBefore(coupon.getStartTime())
//                || now.isAfter(coupon.getEndTime())
                || coupon.getUsedCount() >= coupon.getTotalCount()) {
            return false;
        }

        // 检查适用课程
        if (coupon.getCourseId() != null && !coupon.getCourseId().equals(courseId)) {
            return false;
        }

        // 检查最低消费
        if (amount == null || amount.compareTo(coupon.getMinPurchase()) < 0) {
            return false;
        }

        return true;
    }
}
